<template>
  <base-container>
    <!-- 顶部：租赁类型 / 接单开关 / 营业时间设置 -->
    <OrderListHeader
      :initial-rental-type="rentalType"
      :initial-order-switch="orderSwitchEnabled"
      @rental-type-change="handleRentalTypeChange"
      @order-switch-change="handleOrderSwitchChange"
      @set-business-hours="handleSetBusinessHours"
    />

    <!-- 搜索栏 -->
    <avue-table-search
      :option="searchOption"
      v-model="searchParams"
      @search-change="loadTableSearch"
      @search-reset="loadTableSearchReset"
    />
    <!-- 吸顶TabBar -->

    <div class="sticky-tab-bar">
      <div class="tabbar-container">
        <OrderTabBar
          :tabs="tabsForView"
          :active-tab="activeTab"
          @tab-change="handleTabChange"
          @batch-dispatch="handleBatchDispatch"
          @order-assignment="handleOrderAssignment"
        />
      </div>
    </div>

    <!-- 订单列表 -->
    <div class="order-list">
      <OrderCard
        v-for="order in paginatedOrderList"
        :key="order.id"
        :order-data="order"
        @view="handleOrderView"
        @edit="handleOrderEdit"
        @delete="handleOrderDelete"
        @checkbox-change="handleOrderCheckboxChange"
        @dispatch="handleOrderDispatch"
        @claim="handleOrderClaim"
      />
    </div>

    <!-- 分页组件 -->
    <div class="pagination-container sticky-footer-bar">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        background
        :page-sizes="[10, 20, 50, 100, 200, 500, 1000]"
        :total="totalOrders"
        layout="total, prev, pager, next, sizes, jumper"
        :pager-count="7"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
  </base-container>
</template>

<script setup>
  import { ElMessageBox } from "element-plus";
  import Option from "@/crudOption/order/orderList";
  import OrderListHeader from "./components/List/OrderListHeader.vue";
  import OrderTabBar from "./components/List/OrderTabBar.vue";
  import OrderCard from "./components/List/OrderCard.vue";

  /* 路由 */
  const router = useRouter();

  /* 搜索配置 */
  const { searchOption } = Option();
  const searchParams = ref({});

  /* 顶部状态 */
  const rentalType = ref("all");
  const orderSwitchEnabled = ref(true);

  /* Tab 数据 */
  const activeTab = ref("all");
  const rawTabs = ref([
    { key: "all", label: "全部", count: 552 },
    { key: "pending_payment", label: "待支付", count: 66 },
    { key: "pending_dispatch", label: "待派单", count: 5 },
    { key: "pending_review", label: "待审核", count: 10 },
    { key: "rejected", label: "已拒单", count: 2 },
    { key: "pending_shipment", label: "待发货", count: 8 },
    { key: "pending_receipt", label: "待收货", count: 6 },
    { key: "pending_settlement", label: "待结算", count: 6 },
    { key: "completed", label: "已完成", count: 5 },
    { key: "closed", label: "已关闭", count: 2 },
    { key: "all1", label: "全部", count: 552 },
    { key: "pending_payment1", label: "待支付", count: 66 },
    { key: "pending_dispatch1", label: "待派单", count: 5 },
    { key: "pending_review1", label: "待审核", count: 10 },
    { key: "rejected1", label: "已拒单", count: 2 },
    { key: "pending_shipment1", label: "待发货", count: 8 },
    { key: "pending_receipt1", label: "待收货", count: 6 },
    { key: "pending_settlement1", label: "待结算", count: 6 },
    { key: "completed1", label: "已完成", count: 5 },
    { key: "closed1", label: "已关闭", count: 2 },
    { key: "pending_review2", label: "待审核", count: 10 },
    { key: "rejected2", label: "已拒单", count: 2 },
    { key: "pending_shipment2", label: "待发货", count: 8 },
    { key: "pending_receipt2", label: "待收货", count: 6 },
    { key: "pending_settlement2", label: "待结算", count: 6 },
    { key: "completed2", label: "已完成", count: 5 },
    { key: "closed2", label: "已关闭", count: 2 },
  ]);

  const tabsForView = computed(() => {
    const map = new Map();
    rawTabs.value.forEach(t => !map.has(t.key) && map.set(t.key, t));
    return [...map.values()];
  });

  /* 分页相关 */
  const currentPage = ref(1);
  const pageSize = ref(10);
  const totalOrders = ref(0);

  /* 示例列表 */
  const orderList = ref([
    {
      id: 1,
      orderNo: "12345678900987654321",
      status: "pending_payment",
      createTime: "2025-03-20 09:15:18",
      confirmTime: "2025-03-20 09:15:18",
      amount: 299,
      customerName: "张三",
      isZhima: true,
      customerPhone: "13800138001",
      productName:
        "商品名称商品名称商品商品名称商品名称商品商品名称商品名称商品商品名称商品名称商品商品名称商品名称商品…",
      rentalPeriod: "2025-03-16至2026-06-13 (共455天)",
      deposit: 500,
      storeName: "大鱼租机(7058788)",

      // 商品信息字段
      productId: "12345678900987654321",
      productImage: "src/assets/temp_product.png",
      productColor: "群青色/512GB",
      rentalMethod: "租完归还/买断",

      // 费用详情 - 芝麻免押
      frozenAmount: "235266.00", // 冻结额度（芝麻免押用）
      creditReduction: "234000.00", // 信用减免（芝麻免押用）
      actualDeposit: "1266.00", // 实付押金（芝麻免押用）
      paidDeposit: "1266.00", // 已支付押金
      referenceDeposit: "235266.00", // 参考押金（押金支付用）
      qingyunReduction: "234000.00", // 青云免押（押金支付用）
      requiredDeposit: "1266.00", // 需支付押金（押金支付用）
      rent: "1999.00", // 租金
      monthlyRent: "1999.00", // 月租金
      totalRent: "235266.00", // 总租金
      firstRent: "1216.00", // 首期租金
      lateFee: "1312.00", // 滞纳金
      discountAmount: "1312.00", // 优惠金额
      periods: "12", // 期数
      valueAddedService: "298.00", // 增值服务
      insuranceService: "99.00", // 保险服务
      extendedWarranty: "199.00", // 延保服务
      screenProtection: "99.00", // 碎屏服务
      insurance: "199.00", // 保险

      // 付款信息字段
      installmentAmount: "130235.00",
      currentRent: "¥199999.99",
      buyoutPrice: "130235.00",
      paymentTime: "2025-06-20 14:37:43",
      returnDate: "2025-06-20",
      actualAmount: "12300.21",

      // 用户信息字段
      address:
        "广西壮族自治区桂林市临桂区广西壮族自治区桂林市临桂区广广西壮族自治区桂林市临桂区广西壮族自治区桂林市临桂区广",
      registeredPhone: "13800138001",
      orderNote: "跟进人大鱼",
      noteTime: "2025-03-20 09:15:18",
      claimer: "大鱼",
      // 担保信息字段
      guaranteeMerchant: "Geoff名字",
      guaranteePhone: "17600300012",
      guaranteeStatus: "待确认",
      orderType: "enterprise", // 订单类型：enterprise-企业订单，individual-个人订单
      orderOwnership: "平台订单",
      orderSource: "平台订单",
      channelGroup: "平台",
      channelSource: "青云租",
      orderPlatform: "微信",
      registrationSource: "平台",
      promotionChannel: "平台",
      zhimaChannel: "芝麻租赁",

      // 状态相关时间字段
      dispatchTime: null,
      rejectTime: null,
      reviewTime: null,
      shipTime: null,
      receiptTime: null,
      applyTime: null,
      completeTime: null,
      closeTime: null,

      // 其他字段
      checked: false,
      // 按钮显示逻辑字段
      isProxyDispatch: false, // 是否为代派订单
      isAssigned: false, // 是否已分配
      isClaimed: false, // 是否已认领
    },
    {
      id: 2,
      orderNo: "ORD20241201002",
      status: "pending_dispatch",
      createTime: "2024-12-01 11:15:00",
      amount: 199,
      customerName: "李四",
      isZhima: false,
      customerPhone: "13800138002",
      productName: "iPad Pro 12.9寸",
      rentalPeriod: 15,
      deposit: 300,
      storeName: "小鱼租机(7058789)",

      // 商品信息字段
      productId: "ORD20241201002",
      productImage: "src/assets/temp_product.png",
      productColor: "深空灰色/256GB",
      rentalMethod: "租完归还",

      // 费用详情 - 押金支付
      frozenAmount: "0.00", // 冻结额度（芝麻免押用）
      creditReduction: "0.00", // 信用减免（芝麻免押用）
      actualDeposit: "300.00", // 实付押金（芝麻免押用）
      paidDeposit: "300.00", // 已支付押金
      referenceDeposit: "300.00", // 参考押金（押金支付用）
      qingyunReduction: "0.00", // 青云免押（押金支付用）
      requiredDeposit: "300.00", // 需支付押金（押金支付用）
      rent: "1299.00", // 租金
      monthlyRent: "1299.00", // 月租金
      totalRent: "19485.00", // 总租金
      firstRent: "1299.00", // 首期租金
      lateFee: "0.00", // 滞纳金
      discountAmount: "0.00", // 优惠金额
      periods: "15", // 期数
      valueAddedService: "199.00", // 增值服务
      insuranceService: "99.00", // 保险服务
      extendedWarranty: "100.00", // 延保服务
      screenProtection: "99.00", // 碎屏服务
      insurance: "100.00", // 保险

      // 付款信息字段
      installmentAmount: "1299.00",
      currentRent: "¥1299.00",
      buyoutPrice: "8999.00",
      paymentTime: "2024-12-01 11:30:00",
      returnDate: "2025-01-01",
      actualAmount: "1498.00",

      // 用户信息字段
      address: "北京市朝阳区三里屯街道...",
      registeredPhone: "13800138002",
      orderNote: "客户要求加急处理",
      noteTime: "2024-12-01 11:15:00",
      claimer: "李四",
      // 担保信息字段
      guaranteeMerchant: "张三",
      guaranteePhone: "13800138002",
      guaranteeStatus: "已确认",
      orderType: "individual", // 订单类型：enterprise-企业订单，individual-个人订单
      orderOwnership: "平台订单",
      orderSource: "平台订单",
      channelGroup: "平台",
      channelSource: "青云租",
      orderPlatform: "APP",
      registrationSource: "平台",
      promotionChannel: "平台",
      zhimaChannel: "芝麻租赁",

      // 状态相关时间字段
      dispatchTime: null,
      rejectTime: null,
      reviewTime: null,
      shipTime: null,
      receiptTime: null,
      applyTime: null,
      completeTime: null,
      closeTime: null,

      // 其他字段
      checked: false,
      // 按钮显示逻辑字段
      isProxyDispatch: false, // 是否为代派订单
      isAssigned: false, // 是否已分配
      isClaimed: false, // 是否已认领
    },
    {
      id: 3,
      orderNo: "ORD20241201003",
      status: "pending_review",
      createTime: "2024-12-01 12:00:00",
      dispatchTime: "2024-12-01 12:30:00",
      amount: 399,
      customerName: "王五",
      isZhima: true,
      customerPhone: "13800138003",
      productName: "Dell XPS 15",
      rentalPeriod: 45,
      deposit: 600,
      storeName: "大鱼租机(7058788)",
      // 费用详情
      frozenAmount: "15000.00", // 参考押金
      creditReduction: "14400.00", // 青云免押
      actualDeposit: "600.00", // 需支付押金
      paidDeposit: "600.00", // 已支付押金
      rent: "2599.00", // 租金
      monthlyRent: "2599.00", // 月租金
      valueAddedService: "399.00", // 增值服务
      insuranceService: "199.00", // 保险服务
      extendedWarranty: "200.00", // 延保服务
    },
    {
      id: 4,
      orderNo: "ORD20241201004",
      status: "rejected",
      createTime: "2024-12-01 13:00:00",
      rejectTime: "2024-12-01 13:30:00",
      amount: 149,
      customerName: "赵六",
      isZhima: false,
      customerPhone: "13800138004",
      productName: "Surface Pro 9",
      rentalPeriod: 20,
      deposit: 250,
      storeName: "大鱼租机(7058788)",
      // 费用详情
      frozenAmount: "0.00",
      creditReduction: "0.00",
      actualDeposit: "250.00",
      paidDeposit: "250.00",
      rent: "899.00",
      monthlyRent: "899.00",
      valueAddedService: "149.00",
      insuranceService: "49.00",
      extendedWarranty: "100.00",
      // 按钮显示逻辑字段
      isProxyDispatch: false, // 是否为代派订单
      isAssigned: false, // 是否已分配
      isClaimed: false, // 是否已认领
    },
    {
      id: 5,
      orderNo: "ORD20241201005",
      status: "pending_shipment",
      createTime: "2024-12-01 14:00:00",
      reviewTime: "2024-12-01 14:30:00",
      amount: 89,
      customerName: "钱七",
      isZhima: true,
      customerPhone: "13800138005",
      productName: "iPad Air 5",
      rentalPeriod: 7,
      deposit: 150,
      storeName: "大鱼租机(7058788)",
      // 费用详情
      frozenAmount: "5000.00",
      creditReduction: "4850.00",
      actualDeposit: "150.00",
      paidDeposit: "150.00",
      rent: "599.00",
      monthlyRent: "599.00",
      valueAddedService: "89.00",
      insuranceService: "39.00",
      extendedWarranty: "50.00",
      // 按钮显示逻辑字段
      isProxyDispatch: false, // 是否为代派订单
      isAssigned: false, // 是否已分配
      isClaimed: false, // 是否已认领
    },
    {
      id: 6,
      orderNo: "ORD20241201006",
      status: "pending_receipt",
      createTime: "2024-12-01 15:00:00",
      shipTime: "2024-12-01 15:30:00",
      amount: 199,
      customerName: "孙八",
      isZhima: false,
      customerPhone: "13800138006",
      productName: "iPhone 15 Pro",
      rentalPeriod: 14,
      deposit: 400,
      storeName: "大鱼租机(7058788)",
      // 费用详情
      frozenAmount: "0.00",
      creditReduction: "0.00",
      actualDeposit: "400.00",
      paidDeposit: "400.00",
      rent: "1299.00",
      monthlyRent: "1299.00",
      valueAddedService: "199.00",
      insuranceService: "99.00",
      extendedWarranty: "100.00",
      // 按钮显示逻辑字段
      isProxyDispatch: false, // 是否为代派订单
      isAssigned: false, // 是否已分配
      isClaimed: false, // 是否已认领
    },
    {
      id: 7,
      orderNo: "ORD20241201007",
      status: "renting",
      createTime: "2024-12-01 16:00:00",
      receiptTime: "2024-12-01 16:30:00",
      amount: 299,
      customerName: "周九",
      isZhima: true,
      customerPhone: "13800138007",
      productName: "MacBook Air M2",
      rentalPeriod: 21,
      deposit: 350,
      storeName: "大鱼租机(7058788)",
      // 费用详情
      frozenAmount: "12000.00",
      creditReduction: "11650.00",
      actualDeposit: "350.00",
      paidDeposit: "350.00",
      rent: "1999.00",
      monthlyRent: "1999.00",
      valueAddedService: "299.00",
      insuranceService: "149.00",
      extendedWarranty: "150.00",
      // 按钮显示逻辑字段
      isProxyDispatch: false, // 是否为代派订单
      isAssigned: false, // 是否已分配
      isClaimed: false, // 是否已认领
    },
    {
      id: 8,
      orderNo: "ORD20241201008",
      status: "pending_settlement",
      createTime: "2024-12-01 17:00:00",
      applyTime: "2024-12-01 17:30:00",
      amount: 199,
      customerName: "吴十",
      isZhima: false,
      customerPhone: "13800138008",
      productName: "iPad Pro 11寸",
      rentalPeriod: 28,
      deposit: 300,
      storeName: "大鱼租机(7058788)",
      // 费用详情
      frozenAmount: "0.00",
      creditReduction: "0.00",
      actualDeposit: "300.00",
      paidDeposit: "300.00",
      rent: "1199.00",
      monthlyRent: "1199.00",
      valueAddedService: "199.00",
      insuranceService: "99.00",
      extendedWarranty: "100.00",
      // 按钮显示逻辑字段
      isProxyDispatch: false, // 是否为代派订单
      isAssigned: false, // 是否已分配
      isClaimed: false, // 是否已认领
    },
    {
      id: 9,
      orderNo: "ORD20241201009",
      status: "completed",
      createTime: "2024-12-01 18:00:00",
      completeTime: "2024-12-01 18:30:00",
      amount: 149,
      customerName: "郑十一",
      isZhima: true,
      customerPhone: "13800138009",
      productName: "Surface Laptop 5",
      rentalPeriod: 14,
      deposit: 200,
      storeName: "大鱼租机(7058788)",
      // 费用详情
      frozenAmount: "8000.00",
      creditReduction: "7800.00",
      actualDeposit: "200.00",
      paidDeposit: "200.00",
      rent: "899.00",
      monthlyRent: "899.00",
      valueAddedService: "149.00",
      insuranceService: "79.00",
      extendedWarranty: "70.00",
      // 按钮显示逻辑字段
      isProxyDispatch: false, // 是否为代派订单
      isAssigned: false, // 是否已分配
      isClaimed: false, // 是否已认领
    },
    {
      id: 10,
      orderNo: "ORD20241201010",
      status: "closed",
      createTime: "2024-12-01 19:00:00",
      closeTime: "2024-12-01 19:30:00",
      amount: 99,
      customerName: "王十二",
      isZhima: false,
      customerPhone: "13800138010",
      productName: "iPad mini 6",
      rentalPeriod: 7,
      deposit: 150,
      storeName: "大鱼租机(7058788)",
      // 费用详情
      frozenAmount: "0.00",
      creditReduction: "0.00",
      actualDeposit: "150.00",
      paidDeposit: "150.00",
      rent: "499.00",
      monthlyRent: "499.00",
      valueAddedService: "99.00",
      insuranceService: "49.00",
      extendedWarranty: "50.00",
      // 按钮显示逻辑字段
      isProxyDispatch: false, // 是否为代派订单
      isAssigned: false, // 是否已分配
      isClaimed: false, // 是否已认领
    },
  ]);

  /* 分页计算属性 */
  const paginatedOrderList = computed(() => {
    const start = (currentPage.value - 1) * pageSize.value;
    const end = start + pageSize.value;
    return orderList.value.slice(start, end);
  });

  // 初始化总数量 - 模拟更多数据来测试分页
  totalOrders.value = 100; // 模拟100条数据

  /* 搜索动作 */
  const loadTableSearch = () => {
    const query = {
      ...searchParams.value,
      tab: activeTab.value,
      rentalType: rentalType.value,
      orderSwitchEnabled: orderSwitchEnabled.value,
    };
    console.log("搜索参数:", query);
    // TODO: const { list, counters } = await Api.order.search(query)
    // orderList.value = list; updateTabCounters(counters)
  };
  const loadTableSearchReset = () => {
    searchParams.value = {};
    loadTableSearch();
  };

  /* 事件 */
  const handleRentalTypeChange = v => {
    rentalType.value = v;
    loadTableSearch();
  };
  const handleOrderSwitchChange = v => {
    orderSwitchEnabled.value = v;
    loadTableSearch();
  };
  const handleSetBusinessHours = () => console.log("打开营业时间设置");

  const handleTabChange = k => {
    activeTab.value = k;
    loadTableSearch();
  };
  const handleBatchDispatch = () => console.log("批量派单");
  const handleOrderAssignment = () => console.log("订单分配");

  const handleOrderView = o => {
    console.log("查看订单详情:", o);
    router.push(`/order/order/details?id=${o.id}`);
  };
  const handleOrderEdit = o => console.log("编辑订单:", o);
  const handleOrderDelete = o => {
    ElMessageBox.confirm(`确定要删除订单 ${o.orderNo} 吗？`, "确认删除", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    })
      .then(() => {
        const i = orderList.value.findIndex(x => x.id === o.id);
        if (i > -1) {
          orderList.value.splice(i, 1);
          $msg.success("删除成功");
        }
      })
      .catch(() => $msg.info("已取消删除"));
  };
  const handleOrderCheckboxChange = d => {
    const o = orderList.value.find(x => x.id === d.orderId);
    if (o) o.checked = d.checked;
  };
  const handleOrderDispatch = o => {
    console.log("派单订单:", o);
    $msg.success(`订单 ${o.orderNo} 派单成功`);
  };
  const handleOrderClaim = o => {
    console.log("认领订单:", o);
    $msg.success(`订单 ${o.orderNo} 认领成功`);
  };

  /* 分页事件处理 */
  const handleSizeChange = newSize => {
    pageSize.value = newSize;
    currentPage.value = 1; // 重置到第一页
    console.log("每页显示数量变更:", newSize);
  };

  const handleCurrentChange = newPage => {
    currentPage.value = newPage;
    console.log("当前页变更:", newPage);
  };
</script>

<style scoped lang="scss">
  :deep(.base-search) {
    padding-bottom: 0;
  }
  .tabbar-container {
    position: relative;
    z-index: 101;
    overflow: hidden;
    border-top-right-radius: 12px;
    border-top-left-radius: 12px;
    background-color: var(--bg);
    padding: 0 24px;
    // margin-top: 16px;
  }
  .sticky-tab-bar {
    position: sticky;
    top: 0;
    left: 0;
    right: 0;
    z-index: 102;
    padding: 16px 0 0;
    transition: all 0.3s ease;
    background-color: var(--fl1);
  }
  .sticky-footer-bar {
    position: sticky;
    bottom: 0;
    left: 0;
    right: 0;
    z-index: 1000;
    background: var(--bg);
    transition: all 0.3s ease;
  }
  .order-list {
    background: var(--bg);
    padding: 0 24px;
  }

  .pagination-container {
    display: flex;
    justify-content: flex-end;
    padding: 16px 24px 24px;
    background: var(--bg);
    border-bottom-left-radius: 12px;
    border-bottom-right-radius: 12px;
  }

  // :deep(.custom-pagination) {
  //   .el-pagination__total {
  //     color: var(--ct2);
  //     font-size: 14px;
  //   }

  //   .el-pagination__sizes {
  //     .el-select {
  //       .el-input__inner {
  //         color: var(--ct1);
  //         font-size: 14px;
  //       }
  //     }
  //   }

  //   .el-pager {
  //     li {
  //       color: var(--ct2);
  //       font-size: 14px;

  //       &.is-active {
  //         background-color: var(--bd);
  //         color: white;
  //         border-radius: 4px;
  //       }
  //     }
  //   }

  //   .btn-prev,
  //   .btn-next {
  //     color: var(--ct2);
  //     font-size: 14px;

  //     &:disabled {
  //       color: var(--ct3);
  //     }
  //   }

  //   .el-pagination__jump {
  //     color: var(--ct2);
  //     font-size: 14px;

  //     .el-input__inner {
  //       color: var(--ct1);
  //       font-size: 14px;
  //     }
  //   }
  // }
</style>
